import { query } from '../config/db.js';
import bcrypt from 'bcrypt';
import { generateToken } from '../utils/jwt.js';
import logger from '../config/logger.js';

/**
 * 注册新用户
 */
const registerUser = async (req, res) => {
  try {
    console.log('请求体：', req.body);
    console.log('请求头：', req.headers);
    console.log('请求方法：', req.method);
    console.log('请求路径：', req.path);
    // 检查是否有rawBody属性
    if (req.rawBody) {
      console.log('原始请求体：', req.rawBody);
    }
    const { username, email, password } = req.body || {};
    if (!username || !email || !password) {
      logger.error('请求体缺少必要字段');
      return res.status(400).json({
        message: '请求体缺少必要字段'
      });
    }
    // 检查用户是否已存在
    const existingUser = await query(
      'SELECT * FROM users WHERE username = ? OR email = ?',
      [username, email]
    );
    console.log('用户存在', existingUser);
    if (existingUser.rows.length > 0) {
      return res.status(400).json({
        message: '用户名或邮箱已存在'
      });
    }

    // 加密密码
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(password, salt);

    // 创建新用户
    await query(
      'INSERT INTO users (username, email, password) VALUES (?, ?, ?)',
      [username, email, hashedPassword]
    );

    // 获取创建的用户
    const selectResult = await query(
      'SELECT * FROM users WHERE username = ?',
      [username]
    );

    const user = selectResult.rows[0];
    logger.info(`用户注册成功: ${user.username}`);

    // 生成JWT令牌
    const token = generateToken(user);

    res.status(201).json({
      message: '用户注册成功',
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        created_at: user.created_at
      },
      token
    });
  } catch (error) {
    logger.error('注册用户错误:', error);
    res.status(500).json({
      message: '服务器内部错误'
    });
  }
};

/**
 * 用户登录
 */
const loginUser = async (req, res) => {
  try {
    const { username, password } = req.body;
    // console.log('请求体：', req.body);
    // console.log('请求头：', req.headers);
    // console.log('请求方法：', req.method);
    // console.log('请求路径：', req.path);
    // // 检查是否有rawBody属性
    // if (req.rawBody) {
    //   console.log('原始请求体：', req.rawBody);
    // }

    // 查找用户
    const result = await query('SELECT * FROM users WHERE username = ?', [username]);
    // console.log('查询结果：', result);
    if (result.rows.length === 0) {
      return res.status(401).json({
        message: '无效的凭据'
      });
    }

    const user = result.rows[0];

    // 检查密码
    const isMatch = await bcrypt.compare(password, user.password);

    if (!isMatch) {
      return res.status(401).json({
        message: 'Invalid credentials'
      });
    }

    // Generate JWT token
    const token = generateToken(user);

    logger.info(`用户登录: ${user.username}`);

    res.json({
      message: '登录成功',
      user: {
        id: user.id,
        username: user.username,
        email: user.email
      },
      token
    });
  } catch (error) {
    logger.error('用户登录错误:', error);
    res.status(500).json({
      message: 'Internal server error'
    });
  }
};

/**
 * 获取所有用户
 */
const getUsers = async (req, res) => {
  try {
    const result = await query('SELECT id, username, email, created_at FROM users');

    res.json({
      users: result.rows
    });
  } catch (error) {
    logger.error('获取用户列表错误:', error);
    res.status(500).json({
      message: 'Internal server error'
    });
  }
};

/**
 * 根据ID获取用户
 */
const getUserById = async (req, res) => {
  try {
    const { id } = req.params;

    const result = await query('SELECT id, username, email, created_at FROM users WHERE id = ?', [id]);

    if (result.rows.length === 0) {
      return res.status(404).json({
        message: '用户不存在 getUserById'
      });
    }

    res.json({
      user: result.rows[0]
    });
  } catch (error) {
    logger.error('根据ID获取用户错误:', error);
    res.status(500).json({
      message: 'Internal server error'
    });
  }
};

/**
 * 更新用户
 */
const updateUser = async (req, res) => {
  try {
    const { id } = req.params;
    console.log('请求参数：', req.body);
    const { username, email, password } = req.body;

    // 检查用户是否存在
    const existingUser = await query('SELECT * FROM users WHERE id = ?', [id]);

    if (existingUser.rows.length === 0) {
      return res.status(404).json({
        message: '用户不存在 updateUser'
      });
    }

    // 准备更新字段
    const updateFields = [];
    const params = [];
    let paramIndex = 1;

    if (username) {
      updateFields.push(`username = ?`);
      params.push(username);
    }

    if (email) {
      updateFields.push(`email = ?`);
      params.push(email);
    }

    if (password) {
      const salt = await bcrypt.genSalt(10);
      const hashedPassword = await bcrypt.hash(password, salt);
      updateFields.push(`password = ?`);
      params.push(hashedPassword);
    }

    updateFields.push(`updated_at = CURRENT_TIMESTAMP`);
    params.push(id);

    // 更新用户
    const updateQuery = `UPDATE users SET ${updateFields.join(', ')} WHERE id = ?`;
    // console.log('更新查询 sql 语句：', updateQuery);
    // console.log('更新查询参数：', params);
    // res.status(500).json({
    //   message: '调试更新查询 sql 语句',
    //   sql: updateQuery,
    //   params
    // });
    // return
    // 执行更新
    const updateResult = await query(
      updateQuery,
      params
    );
    // res.status(500).json({
    //   message: '调试更新查询 sql 语句',
    //   sql: updateQuery,
    //   params,
    //   updateResult
    // });
    // return
    // 获取更新后的用户数据
    const selectResult = await query(
      'SELECT id, username, email, created_at, updated_at FROM users WHERE id = ?',
      [id]
    );

    logger.info(`用户更新: ${selectResult.rows[0].username}`);

    res.json({
      message: '用户更新成功',
      user: selectResult.rows[0]
    });
  } catch (error) {
    logger.error('更新用户错误:', error);
    res.status(500).json({
      message: '更新用户失败'
    });
  }
};

/**
 * 删除用户
 */
const deleteUser = async (req, res) => {
  console.log('请求参数params:deleteUser：', req.params);
  try {
    const { id } = req.params;

    // 检查用户是否存在
    const existingUser = await query('SELECT * FROM users WHERE id = ?', [id]);

    if (existingUser.rows.length === 0) {
      return res.status(404).json({
        message: '用户不存在 deleteUser'
      });
    }

    // 删除用户
    await query('DELETE FROM users WHERE id = ?', [id]);

    logger.info(`用户删除: ${existingUser.rows[0].username}`);

    res.json({
      message: '用户删除成功'
    });
  } catch (error) {
    logger.error('删除用户错误:', error);
    res.status(500).json({
      message: '删除用户失败'
    });
  }
};

/**
 * 获取用户权限
 */
const getUserPermissions = async (req, res) => {
  try {
    console.log('请求参数params:getUserPermissions：', req.params);
    const { id } = req.params;
    // 检查用户是否存在
    {
      const existingUser = await query('SELECT * FROM users WHERE id = ?', [id]);

      if (existingUser.rows.length === 0) {
        return res.status(404).json({
          message: '用户不存在 getUserPermissions'
        });
      }
    }

    // 获取用户权限
    const result = await query(
      `
        SELECT p.id, p.name, p.description
        FROM permissions p
        JOIN user_permissions up ON p.id = up.permission_id
        WHERE up.user_id = ?
      `,
      [id]
    );

    res.json({
      permissions: result.rows
    });
  } catch (error) {
    logger.error('获取用户权限错误:', error);
    res.status(500).json({
      message: '获取用户权限失败'
    });
  }
};

/**
 * 添加权限给用户
 */
const addPermissionToUser = async (req, res) => {
  console.log('请求参数body：addPermissionToUser:', req.body);

  try {
    const { userId, permissionId } = req.body;

    // 检查用户是否存在
    {
      const existingUser = await query('SELECT * FROM users WHERE id = ?', [userId]);
      if (existingUser.rows.length === 0) {
        return res.status(404).json({
          message: '用户不存在 addPermissionToUser'
        });
      }
    }

    // 检查权限是否存在
    {
      const existingPermission = await query('SELECT * FROM permissions WHERE id = ?', [permissionId]);

      if (existingPermission.rows.length === 0) {
        return res.status(404).json({
          message: '权限不存在 addPermissionToUser'
        });
      }
    }

    // 检查用户是否已拥有该权限
    {
      const userPermission = await query(
        'SELECT * FROM user_permissions WHERE user_id = ? AND permission_id = ?',
        [userId, permissionId]
      );

      if (userPermission.rows.length > 0) {
        return res.status(400).json({
          message: '用户已拥有该权限'
        });
      }
    }

    // 添加权限给用户
    {
      const addPermissionResult = await query(
        'INSERT INTO user_permissions (user_id, permission_id) VALUES (?, ?)',
        [userId, permissionId]
      );
      console.log('添加权限结果：', addPermissionResult);

      logger.info(`权限 ${addPermissionResult.insertId} 已添加给用户 ${userId}`);

      res.json({
        message: '权限添加成功'
      });
    }

  } catch (error) {
    logger.error('添加用户权限错误:', error);
    res.status(500).json({
      message: '添加用户权限失败'
    });
  }
};

/**
 * 从用户移除权限
 */
const removePermissionFromUser = async (req, res) => {
  console.log('请求参数body:removePermissionFromUser：', req.body);  
  try {
    const { userId, permissionId } = req.body;

    // 检查用户是否存在
    const existingUser = await query('SELECT * FROM users WHERE id = ?', [userId]);

    if (existingUser.rows.length === 0) {
      return res.status(404).json({
        message: '用户不存在 removePermissionFromUser'
      });
    }

    // 检查权限是否存在
    const existingPermission = await query('SELECT * FROM permissions WHERE id = ?', [permissionId]);

    if (existingPermission.rows.length === 0) {
      return res.status(404).json({
        message: '权限不存在'
      });
    }

    // 检查用户是否拥有该权限
    const userPermission = await query(
      'SELECT * FROM user_permissions WHERE user_id = ? AND permission_id = ?',
      [userId, permissionId]
    );

    if (userPermission.rows.length === 0) {
      return res.status(400).json({
        message: '用户没有该权限'
      });
    }

    // 从用户移除权限
    await query(
      'DELETE FROM user_permissions WHERE user_id = ? AND permission_id = ?',
      [userId, permissionId]
    );

    logger.info(`权限 ${existingPermission.rows[0].name} 已从用户 ${existingUser.rows[0].username} 移除`);

    res.json({
      message: '权限移除成功'
    });
  } catch (error) {
    logger.error('移除用户权限错误:', error);
    res.status(500).json({
      message: '移除用户权限失败'
    });
  }
};

export {
  registerUser,
  loginUser,
  getUsers,
  getUserById,
  updateUser,
  deleteUser,
  getUserPermissions,
  addPermissionToUser,
  removePermissionFromUser
};